import styles from './index.module.scss';
import { NavBar, TextArea, Toast } from 'antd-mobile';
import { useDispatch } from 'react-redux';
import { useAppSelector } from '@/store';

import { useState } from 'react';
import {
  submitCommentAction,
  getArticleComByIdAction,
  getCommentByIdAction,
} from '@/store/action/comment';
type Props = {
  // 评论的作者的名字
  name?: string;
  onBack: () => void;
};
export default function CommentInput({ name, onBack }: Props) {
  const dispatch = useDispatch();
  const { detail } = useAppSelector((state) => state.article);
  const [value, setValue] = useState('');
  const { originComment } = useAppSelector((state) => state.comments);

  const handleSubmit = async () => {
    // 逻辑判断 如果存在原始数据的com_id表示对回复评论
    if (originComment.com_id) {
      await dispatch(
        submitCommentAction(originComment.com_id, value, detail.art_id)
      );
      // 重新获取评论的action 渲染页面
      dispatch(getCommentByIdAction(originComment.com_id));
      // 提示成关闭界面
      Toast.show({ content: '发表成功' });
      onBack();
      return;
    }
    // 如果不存在com_id,表示对文章进行评论调用接口
    await dispatch(submitCommentAction(detail.art_id, value));
    // 提示用户
    Toast.show({ content: '文章发布成功' });
    // 更新数据
    dispatch(getArticleComByIdAction({ type: 'a', source: detail.art_id }));
    // 关闭弹出层
    onBack();
  };
  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span onClick={handleSubmit} className="publish">
            发表
          </span>
        }
        onBack={onBack}
      >
        {name ? '回复评论' : '评论文章'}
      </NavBar>
      <div className="input-area">
        {/* 回复别人的评论时显示：@某某 */}
        {name && <div className="at">@{name}:</div>}

        {/* 评论内容输入框 */}
        <TextArea
          placeholder="说点什么~"
          rows={10}
          value={value}
          onChange={(strVal) => setValue(strVal)}
        />
      </div>
    </div>
  );
}
